package login;

import javax.swing.*;
import java.awt.event.*;
import utils.FileUtils;

public class RegisterFrame extends JFrame implements ActionListener {
    private JTextField userField;
    private JPasswordField passField;
    private JButton registerButton;
    private static final String FILE_NAME = "users.txt";

    public RegisterFrame() {
        setTitle("注册");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLayout(null);

        JLabel userLabel = new JLabel("用户名:");
        userLabel.setBounds(30, 40, 80, 25);
        add(userLabel);

        userField = new JTextField(20);
        userField.setBounds(110, 40, 150, 25);
        add(userField);

        JLabel passLabel = new JLabel("密码:");
        passLabel.setBounds(30, 80, 80, 25);
        add(passLabel);

        passField = new JPasswordField(20);
        passField.setBounds(110, 80, 150, 25);
        add(passField);

        registerButton = new JButton("注册");
        registerButton.setBounds(110, 120, 80, 30);
        registerButton.addActionListener(this);
        add(registerButton);

        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String username = userField.getText();
        String password = new String(passField.getPassword());

        if (username.isEmpty() || password.isEmpty()) {
            JOptionPane.showMessageDialog(this, "用户名和密码不能为空！");
            return;
        }
        User newUser = new User(username, password);
        FileUtils.writeUserToFile(newUser, FILE_NAME);
        JOptionPane.showMessageDialog(this, "注册成功！");
        dispose();
    }
}